package com.example.windyweather.ui.place

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.example.windyweather.logic.Repository
import com.example.windyweather.logic.model.Place

class PlaceViewModel : ViewModel() {

    private val searchLiveData = MutableLiveData<String>()

    val placeList = ArrayList<Place>()

    /**
     *  当用户调用searchPlace时，改变searchLiveData大，Transformations.switchMap(searchLiveData)
     *  观察到 searchLiveData 值变化，就会调用lambda函数，从而发起真正的请求，并把请求的返回值liveData对象
     *  转变成UI层可观察的livedata对象 placeLiveData
     */
    val placeLiveData = Transformations.switchMap(searchLiveData) { query ->
        Repository.searchPlace(query)
    }

    fun searchPlace(query: String) {
        searchLiveData.value = query
    }

    fun savePlace(place: Place) = Repository.savePlace(place)

    fun getSavePlace() = Repository.getSavePlace()

    fun isPlaceSaved() = Repository.isPlaceSaved()
}